<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <span>遥测</span>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleAdd">添加遥测数据</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: ICON.DELETE,
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AddModal @register="registerAddModal" @success="handleSuccess" />
    <DeleteModal @register="registerDeleteModal" @success="handleSuccess" />
  </div>
</template>
<script setup lang="ts">
  import { defineProps, onMounted, onDeactivated, onActivated, onBeforeUnmount } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { ICON } from '/@/enums/iconEnum';
  import { telemetryTableSchema, formSchema } from './index.data';
  import { useModal } from '/@/components/Modal';
  import { useWebSocket } from '@vueuse/core';
  import AddModal from '../attributeTable/components/Modal.vue';
  import DeleteModal from './components/DeleteModal.vue';
  import { saveEntityTelemetry, deleteEntityTelemetry } from '/@/api/thingsborad/entity/entity';
  import { saveTelemetryParams } from '/@/api/thingsborad/entity/model/entityModel';
  import {
    publicDrawerTableFormStyleSetting,
    tableStyleSetting,
  } from '/@/settings/thingsBoardDesign';
  const props = defineProps({
    isComponent: {
      type: Boolean,
      default: true,
    },
    entityType: {
      type: String,
      default: '',
    },
    entityId: {
      type: String,
      default: '',
    },
  });
  const [registerTable, { setProps }] = useTable({
    ...tableStyleSetting,
    pagination: { pageSizeOptions: ['10', '20', '30'] },
    formConfig: {
      layout: 'horizontal',
      schemas: formSchema,
      ...publicDrawerTableFormStyleSetting,
      actionColOptions: {
        md: { span: 12, offset: 0 },
        lg: { span: 8, offset: 8 },
        xl: { span: 6, offset: 12 },
        xxl: { span: 6, offset: 16 },
      },
    },
    rowSelection: {
      type: 'checkbox',
    },
  });
  const [registerAddModal, { openModal: openAddModal }] = useModal();
  const [registerDeleteModal, { openModal: openDeleteModal }] = useModal();
  const { data, send, close } = useWebSocket(
    `ws://47.110.73.94:1523/api/ws/plugins/telemetry?token=${localStorage.getItem('jwt_token')}`,
    {
      autoReconnect: false,
      heartbeat: true,
      onConnected: () => {},
      onMessage: () => {
        const values = JSON.parse(data.value);
        let telemetryTableData: Array<any> = [];
        Object.keys(values.data).forEach((item) => {
          telemetryTableData.push({
            lastUpdateTs: values.data[item][0][0],
            key: item,
            value: values.data[item][0][1],
          });
        });
        setProps({
          columns: telemetryTableSchema,
          dataSource: telemetryTableData,
          loading: false,
        });
      },
    },
  );
  // 添加
  const handleAdd = () => {
    openAddModal(true, { mode: 'add' });
  };

  // 删除
  function handleDelete(record: Recordable) {
    openDeleteModal(true, {
      key: record.key,
    });
  }
  // 成功
  const handleSuccess = async ({ key, keys, values }) => {
    if (key == 'add') {
      let telemetryParams: saveTelemetryParams = {
        entityType: props.entityType,
        entityId: props.entityId,
        key: values.keyName,
      };
      switch (values.valueType) {
        case 'string':
          telemetryParams.value = values.stringValue;
          break;
        case 'integer':
          telemetryParams.value = values.integerValue;
          break;
        case 'decimal':
          values.decimalValue = parseFloat(values.decimalValue);
          telemetryParams.value = values.decimalValue;
          break;
        case 'boolean':
          telemetryParams.value = values.booleanValue;
          break;
        case 'json':
          values.jsonValue = JSON.parse(values.jsonValue);
          telemetryParams.value = values.jsonValue;
          break;
      }
      await saveEntityTelemetry(telemetryParams);
      initTelemetryTableData();
    } else if (key == 'delete') {
      let params = {
        entityType: props.entityType,
        entityId: props.entityId,
        obj: {
          keys: keys,
          deleteAllDataForKeys:
            values.deleteStrategy == 'DeleteAllData' ||
            values.deleteStrategy == 'DeleteAllDataExceptLatestValue',
          rewriteLatestIfDeleted: Boolean(values.rewrite),
          deleteLatest:
            Boolean(values.deleteStrategy == 'DeleteAllData') ||
            Boolean(values.deleteStrategy == 'DeleteLatestValue') ||
            Boolean(values.deleteStrategy == 'DeleteAllDataForTimePeriod'),
        },
      };
      await deleteEntityTelemetry(params);
      initTelemetryTableData();
    }
  };

  // 初始化
  onMounted(() => {
    initTelemetryTableData();
    send(
      JSON.stringify({
        tsSubCmds: [
          {
            cmdId: 1,
            entityId: props.entityId,
            entityType: props.entityType,
            scope: 'LATEST_TELEMETRY',
          },
        ],
      }),
    );
  });

  // 获取遥测数据
  const initTelemetryTableData = () => {
    setProps({
      columns: telemetryTableSchema,
      useSearchForm: true,
      loading: true,
    });
  };
  onBeforeUnmount(() => {
    close();
  });
</script>
